<?php
/**
 * Created by PhpStorm.
 * User: 86151 - 姜伟
 * Date: 2022/9/20 16:12.
 */

namespace Xinyu\Gen\Core\Libs;

class ServiceClient extends BaseClient
{
    use SingletonUtil;

    // 获取搜索参数
    public function getSearchQueryParams($search = '', $columnList = [])
    {
        if (empty($search)) {
            return '';
        }
        $searchList = explode(',', $search);
        if (empty($searchList)) {
            return '';
        }
        $searchString = '';
        foreach ($searchList as $v) {
            $searchDesc = $columnList[$v]['comment'] ?? '';
            $searchType = $columnList[$v]['type'] ?? '';
            $queryType = $this->getQueryType($searchType);
            switch ($queryType) {
                case 'between':
                    $itemString = "if (!empty(\$params['search_{$v}s'])) { // 搜索--{$searchDesc}
            \$query->whereBetween('{$v}', \$params['search_{$v}s']);
        }" . PHP_EOL;
                    break;
                case '=':
                    $itemString = "if (!empty(\$params['search_{$v}'])) { // 搜索--{$searchDesc}
            \$query->where('{$v}', \$params['search_{$v}']);
        }" . PHP_EOL;
                    break;
                default:
                    $itemString = "if (!empty(\$params['search_{$v}'])) { // 搜索--{$searchDesc}
            \$query->where('{$v}', 'like', '%' . \$params['search_{$v}'] . '%');
        }" . PHP_EOL;
                    break;
            }
            $searchString .= str_repeat(' ', 8) . $itemString;
        }
        return rtrim($searchString, PHP_EOL);
    }

    // 获取搜索条件的查询类型
    public function getQueryType($searchType)
    {
        switch ($searchType) {
            case 'integer':
            case 'smallint':
            case 'decimal':
            case 'datetime':
                return 'between';
                break;
            case 'string':
            case 'text':
                return 'like';
                break;
            case 'boolean':
                return '=';
                break;
            default:
                return '';
                break;
        }
    }
}
